package com.zksite.nator.server.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.zksite.nator.server.http.initialzer.ForwardServerInitialzer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

@Component
public class ForwardServer implements Runnable {

	private static final Logger LOGGER = LoggerFactory.getLogger(ForwardServer.class);

	@Value("${forward.port}")
	private Integer port;

	private EventLoopGroup workGroup;// 用于网络事件的处理

	private EventLoopGroup bossGruop;// 用于服务器端接受客户端的连接

	@Autowired
	private ForwardServerInitialzer forwardServerInitialzer;

	public void setLoopGroup(EventLoopGroup workGroup, EventLoopGroup bossGruop) {
		this.workGroup = workGroup;
		this.bossGruop = bossGruop;
	}

	public void start() {
		new Thread(this).start();
	}

	@Override
	public void run() {
		try {
			LOGGER.info("start http forwar server on port:{}", port);
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGruop, workGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
					.option(ChannelOption.TCP_NODELAY, true).childHandler(forwardServerInitialzer);// 指定此套接口排队的最大连接个数
			try {
				ChannelFuture f = b.bind(port).sync();
				f.channel().closeFuture().sync();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} finally {
			bossGruop.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}

}
